<template>
  <div class="login_container">
    <div class="login_box">
      <!-- 头像 -->
      <div class="avater_box">
        <img src="../../public/logo.svg" alt="" />
      </div>

      <div class="name">荔享家后台管理系统</div>
      <!-- 登录表单 -->
      <el-form
        ref="loginFormRef"
        :rules="loginFormRules"
        :model="loginForm"
        label-width="0px"
        class="login_form"
      >
        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.user_name"
            placeholder="用户名"
            prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            placeholder="密码"
            prefix-icon="el-icon-lock"
          ></el-input>
        </el-form-item>

        <!-- 按钮区 -->
        <el-form-item class="btns">
          <el-button type="primary" @click="login">登录</el-button>
          <el-button type="info" @click="resetLoginForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import aesEncrypt from '../encrypt'
export default {
  data() {
    return {
      // 这是个登录表单对象
      loginForm: {
        user_name: 'admin',
        password: '87892436'
      },
      // 这是表单的验证规则对象
      loginFormRules: {
        // 验证用户名是否合法
        user_name: [
          { required: true, message: '请输入登录名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度为3到10之间', trigger: 'blur' }
        ],
        // 验证密码是否合法
        password: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          { min: 8, max: 15, message: '长度为8到15之间', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    login() {
      this.$refs.loginFormRef.validate(async (valid) => {
        // if (!valid) return
        // const { data: res } = await this.$http.post(
        //   '/admin/login',
        //   this.loginForm
        // )
        // if (res.code !== 200) return this.$message.error(res.msg)
        // this.$message.success(res.meta.msg)
        // /**
        //  * 1.将登录成功后的 token ，保存到客户端的 sessionStorage 中
        //  *    1.1 项目中除了登录之外的其他api接口，必须在登录之后才能访问
        //  *    1.2 token 只应该在当前网站打开期间生效，所以将 token 保存在 sessionStorage 中
        //  * 2. 通过编程式导航跳转到后台主页，路由地址是 /home
        //  */
        // console.log(res)
        // // 将token保存到sessionStorage中
        // window.sessionStorage.setItem('token', res.data.token)
        // 页面跳转
        // this.$message.success(res.msg)

        // 获取密钥，过期后重新拿
        if (this.aa == null || this.aa.et < new Date().getTime()) {
          const a = await this.$http.get('/userRegLogin')

          if (a.data.status !== 200) {
            this.aa = null
            return
          }
          this.aa = JSON.parse(a.data.data)
          this.aa.id = this.getExId(a.data.data)
        }

        // 数据加密

        const formData = this.loginForm
        const pwd = aesEncrypt(formData.password, this.aa.a.s, this.aa.a.iv)
        const username = formData.user_name

        const { data: res } = await this.$http.post('/login', {
          username: username,
          password: pwd,
          a_id: this.aa.id
        })

        if (res.status !== 200) {
          this.$message.error(res.message)
          return
        }

        // 存储数据
        localStorage.setItem('admin', JSON.stringify(res.data.user))
        localStorage.setItem('token', res.data.token)

        this.$message.success('登录成功')

        setTimeout(() => {
          this.$router.push('/home')
        }, 500)
      })
    },
    getExId(jsonStr) {
      const arr = jsonStr.split(',')
      const ids = arr[arr.length - 1]
      const id = ids.split('}')[0].split(':')[1] + ''

      return id
    },
    // 点击重置按钮，重置登录表单
    resetLoginForm() {
      this.$refs.loginFormRef.resetFields()
    }
  }
}
</script>

<!-- scoped 样式隔离 -->
<style lang="less" scoped>
.login_container {
  background-color: #2b4b6b;
  height: 100%;
}

.login_box {
  width: 500px;
  height: 350px;
  background-color: #fff;
  border-radius: 3px;
  // 居中元素
  position: absolute;
  top: 50%;
  left: 50%;
  // 向xy轴分别平移自己的50%像素
  transform: translate(-50%, -50%);

  .avater_box {
    height: 130px;
    width: 130px;
    border: 3px solid #eee;
    border-radius: 50%;
    // padding: 10px;
    position: absolute;
    top: 0;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    box-shadow: 0 0 10px #ddd;
    display: flex;
    justify-content: center;
    align-items: center;
    img {
      height: 70%;
      width: 70%;
    }
  }

  .name {
    color: #909399;
    font-weight: 700;
    margin-top: 90px;
    text-align: center;
    font-size: 30px;
    letter-spacing: 2px;
  }
}

.login_form {
  position: absolute;
  bottom: 0%;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}

.btns {
  display: flex;
  justify-content: flex-end;
}
</style>
